package com.lalu.clapperboard;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceActivity;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;

public class Preferences extends PreferenceActivity {
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);                     
    		
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

            Preference title = (Preference) findPreference("TITLE");
            title.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "Title (modified): " + prefs.getString("TITLE", null) + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
            	}
    	        return true;
            }
            });
            
            Preference director = (Preference) findPreference("DIRECTOR");
            director.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "Director (modified): " + prefs.getString("DIRECTOR", null) + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
            	}
    	        return true;
            }
            });
            
            Preference cameraman = (Preference) findPreference("CAMERAMAN");
            cameraman.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "Cameraman (modified): " + prefs.getString("CAMERAMAN", null) + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
            	}
    	        return true;
            }
            });
            
            Preference standard = (Preference) findPreference("STANDARD");
            standard.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "Standard (modified): " + prefs.getString("STANDARD", null) + "\n" + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
            	}
    	        return true;
            }
            });
            
            Preference location = (Preference) findPreference("LOCATION");
            location.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "\n" + "Location (modified): " + prefs.getString("LOCATION", null) + "\n" + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
            	}
    	        return true;
            }
            });
            
            Preference misc = (Preference) findPreference("MISC");
            misc.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            	 public boolean onPreferenceChange(Preference preference, Object newValue) {
            		if (String.valueOf(prefs.getString("MISC", null)) != null) {
            		String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	        	String fname = "clapperboard.txt";
    	        	String extState = Environment.getExternalStorageState();
    	        	if (extState.equals(Environment.MEDIA_MOUNTED)) {
       	        	 try {
       	        		final FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
       	        		gOut.append("\n" + "\n" + "Miscelaneous (modified): " + prefs.getString("MISC", null) + "\n" + "\n");
       	        		gOut.flush();
	       	   	        gOut.close();
	       	   	        /*
	       	   	        Context context = getApplicationContext();
	       	   	        int duration = Toast.LENGTH_SHORT;
	       	   	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + fname + ".", duration);
	       	   	        toast.show();
	       	   	        */
	       	        	 }
	       	        	 catch (IOException ioe) {
	   	                 ioe.printStackTrace();
	       	        	 }
    	        	}
            		}
    	        return true;
            }
            });
            
            Preference about = (Preference) findPreference("ABOUT");
            about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            	public boolean onPreferenceClick(Preference preference) {
            		AlertDialog.Builder alertbox = new AlertDialog.Builder(Preferences.this);
          	      	alertbox.setMessage("This application is developed by Lalu." + "\n" + "If you like it, you can say 'Thanks' at: bboylalu@gmail.com" + "\n" + "Clapperboard is free and open source (you can search it on http://code.google.com), so feel free to use it for whatever purpose you want. " +
          	      			"I made it, first of all, for personal use, but if it helps you, please let me know and maybe give me some credits (in whatever hidden place you wish :D). Thanks.");
          	      	alertbox.show();
          	      	return true;
            	}
            });
            
            Preference help = (Preference) findPreference("HELP");
            help.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            	public boolean onPreferenceClick(Preference preference) {
            		AlertDialog.Builder alertbox = new AlertDialog.Builder(Preferences.this);
          	      	alertbox.setMessage("Help page" + "\n" + "\n" + "\n" + "This application is designed to work as a movie clapperboard, which should help you getting your project organized and synchronize audio and video recorded with diferrent equipment." + "\n" + "\n" + 
          	      			"Clapperboard allows you to customize the content displayed on screen, with information as the director, cameraman and title of the movie, and providing a timecode which displays the time in HH:MM:SS:FF format." + "\n" + "\n" + 
          	      			"The application also saves a document in text (*.txt) format on your SD card, allowing you to keep track of your footage."+ "\n" + "\n" + "Changing any value will be added to the file next time you trigger the clapperboard." + "\n" + "\n" +
          	      			"Make sure that the file clapperboard.txt located on your SD card is not opened by any application, so the program can write data to it." + "\n" + "\n" +
          	      			"*Please note that the app will be displayed correctly only on MDPI screens (320x480 screen resolution).");
          	      	alertbox.show();
          	      	return true;
            	}
            });
            
            Preference reset = (Preference) findPreference("RESET");
            reset.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            	public boolean onPreferenceClick(Preference preference) {
            		AlertDialog.Builder alt_bld = new AlertDialog.Builder(Preferences.this);
            		alt_bld.setMessage("Are you sure you want to reset the timecode to 00:00:00:00?" + "\n" + "This will also overwrite the clapperboard.txt file and you will lose all saved data." + "\n" + "First, you should make a backup of the clapperboard.txt file.")
            		.setCancelable(true)
            		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            			public void onClick(DialogInterface dialog, int id) {         				
            	        	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getString(R.string.package_name)+"/files/";
            	        	String fname = "millis.txt";
            	        	// Current state of the external media
            	            String extState = Environment.getExternalStorageState();

            	            // External media can be written onto
            	            if (extState.equals(Environment.MEDIA_MOUNTED)) {
            	        	 try {
            	                 // Make sure the path exists
            	                 boolean exists = (new File(path)).exists();  
            	                 if (!exists){ new File(path).mkdirs(); }  

            	                 // Open output stream
            	                 FileWriter gOut = new FileWriter(path + fname, false);
            	                 FileWriter fOut = new FileWriter("/sdcard/clapperboard.txt", false);
            	                 
            	                 gOut.write("0");
            	                 fOut.write(String.valueOf("Title: " + prefs.getString("TITLE", null) + "\n" + "\n"));
            	       	         fOut.write(String.valueOf("Director: " + prefs.getString("DIRECTOR", null) + "\n" + "\n"));
            	       	         fOut.write(String.valueOf("Cameraman: " + prefs.getString("CAMERAMAN", null) + "\n" + "\n"));
            	       	         fOut.write(String.valueOf("Standard: " + prefs.getString("STANDARD", null) + "\n" + "\n"));

            	                 // Close output stream
            	                 gOut.flush();
            	                 gOut.close();
            	                 /*
            	                 Context context = getApplicationContext();
            	       	         int duration = Toast.LENGTH_SHORT;
            	       	         Toast toast = Toast.makeText(context, "MILLIS wrote to " + path + fname + ".", duration);
            	       	         toast.show();
            	       	         */
            	             } 
            	        	 catch (IOException ioe) {
            	                 ioe.printStackTrace();
            	             }
            			}
            		}})
            		.setNegativeButton("No", new DialogInterface.OnClickListener() {
            			public void onClick(DialogInterface dialog, int id) {
            				dialog.cancel();
            			}
            		});
            		AlertDialog alert = alt_bld.create();
            		alert.setTitle("Reset");
            		alert.show();
            		
             		return true;
            	}
            });
            
    }
}
